package com.cn.zsc.service;

import com.cn.zsc.db108.dao.AccountAMapper;
import com.cn.zsc.db108.model.AccountA;
import com.cn.zsc.dblocal.dao.AccountBMapper;
import com.cn.zsc.dblocal.model.AccountB;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Service
public class AccountService {

    @Resource
    private AccountBMapper accountBMapper;

    @Resource
    private AccountAMapper accountAMapper;

    @Transactional(transactionManager = "tm108",rollbackFor = Exception.class)
    public void transferAccount(){
        AccountA accountA = accountAMapper.selectByPrimaryKey(1);
        accountA.setBalance(accountA.getBalance().subtract(BigDecimal.valueOf(200)));
        accountAMapper.updateByPrimaryKey(accountA);
        try{
            AccountB accountB = accountBMapper.selectByPrimaryKey(1);
            accountB.setBalance(accountB.getBalance().add(BigDecimal.valueOf(200)));
            accountBMapper.updateByPrimaryKey(accountB);
            int i = 1/0;
        }catch (Exception e){
            // 补偿机制
            AccountB accountb = accountBMapper.selectByPrimaryKey(1);
            accountb.setBalance(accountb.getBalance().subtract(BigDecimal.valueOf(200)));
            accountBMapper.updateByPrimaryKey(accountb);
            throw e;
        }
    }
}
